package xin.marcher.module.rights.service.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.rights.domain.dto.RoleDTO;
import xin.marcher.module.rights.domain.dto.UserRoleRelationDTO;
import xin.marcher.module.rights.domain.request.QueryRoleRequest;
import xin.marcher.module.rights.domain.request.RemoveRoleRequest;
import xin.marcher.module.rights.domain.request.RoleRequest;
import xin.marcher.module.rights.repository.RightsRepository;
import xin.marcher.module.rights.service.RoleService;

import java.util.List;
import java.util.Objects;

/**
 *
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RightsRepository rightsRepository;

    @Override
    @Transactional
    public JsonResult saveRole(RoleRequest request) {
        // 校验角色编码
        RoleDTO roleDTO = rightsRepository.queryRoleByRoleCode(request.getRoleCode());
        if (Objects.nonNull(roleDTO)) {
            return JsonResult.buildError("角色编码已存在");
        }
        // 保存角色
        Long roleId = rightsRepository.saveRole(request);
        // 保存角色关联的权限
        rightsRepository.saveRolePermissionRelation(roleId, request);
        return JsonResult.buildSuccess();
    }

    @Override
    @Transactional
    public JsonResult removeRole(RemoveRoleRequest request) {
        // 校验角色是不是已经分配给了用户
        List<UserRoleRelationDTO> userRoleRelationDTOS = rightsRepository.queryUserRoleRelationByRoleId(request.getRoleId());
        if (CollectionUtils.isNotEmpty(userRoleRelationDTOS)) {
            return JsonResult.buildError("角色已经分配给了用户无法删除");
        }
        // 删除角色和权限的关联关系
        rightsRepository.removeRolePermissionRelationByRoleId(request.getRoleId());
        // 删除角色
        rightsRepository.removeRole(request);
        return JsonResult.buildSuccess();
    }

    @Override
    public PageResult<RoleDTO> queryRole(QueryRoleRequest request) {
        return rightsRepository.queryRole(request);
    }
}
